<?php
class User_Model_DbTable_User extends Custom_Db_Table_Abstract
{
    public $_name = 'user';
    
    
    public function validateLogin($data)
    {
        $adapter = $this->getAuthAdapter();
        $adapter->setIdentity($data['username'])
                ->setCredential(md5($data['password']));
        
        $auth    = Zend_Auth::getInstance();
        $result  = $auth->authenticate($adapter);
        
        if ($result->isValid()) {
            $user = $adapter->getResultRowObject();
			$objRole = new User_Model_DbTable_Role();
			$role = $objRole->getOne($user->role_id);
            $user->role = $role['role_name'];

            $auth->getStorage()->write($user);
		
			if($data['rememberMe'])
			{
				Zend_Session::rememberMe(60*60*24*7);
			}
			else
			{
				Zend_Session::forgetMe();
			}   
    		$this->_logger->info('User '. $user->user_fullname. ' Logged in');
            return true;
         
        }
        else
        {
            return false;
        }    
        
    }
    
    
    public function getAuthAdapter()
    {
        $db_adapter = self::getDefaultAdapter();
        $auth_adapter = new Zend_Auth_Adapter_DbTable($db_adapter);
        
        $auth_adapter->setTableName($this->_name)
                            ->setIdentityColumn('username')
                            ->setCredentialColumn('password');
         
        return $auth_adapter;
    }
    
    public function save($data)
    {
        $data['password'] = md5($data['password']);
        return( $this->insert($data));
    }
    
    public function getUserWithRoles($searchkey='')
    {
        $role = new User_Model_DbTable_Role();
        $member = new User_Model_DbTable_UserMembership();
        if($searchkey)
        {    
            $where = "user.username like '%$searchkey%' OR user_fullname like '%$searchkey%' OR user_email like '%$searchkey%' OR role.role_name='$searchkey'";
        }    
        else
         $where = "1 = 1";   
        $select = $this->select()
                ->setIntegrityCheck(false)
                ->from(array('user' => $this->_name), array('user.*'))
                ->join(array('role' => $role->_name), 'user.role_id = role.id', array('role.role_name'))
                ->join(array('member'=>$member->_name),'user.id=member.user_id AND member.record_type="CURRENT" AND member.status!="DELETED"',array('member.status'))
                ->where($where)
                ->order($this->getOrderBy());
        return $this->_applyPaginator($select)->toArray();
    }
    
}

?>
